package com.yunxi.service.dubboService.impl.sto;

import com.alibaba.cloud.context.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunxi.bizToHub.pojo.CanSendResourcesVO;
import com.yunxi.bizToHub.service.DespatchOrderDubboService;
import com.yunxi.core.base.Constant;
import com.yunxi.core.util.BeanTools;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.dealer.pojo.PartnerStorageVO;
import com.yunxi.dealer.pojo.PartnerVO;
import com.yunxi.dealer.service.PartnerStorageDubboService;
import com.yunxi.finance.service.DynamicRebateCommissionDubboService;
import com.yunxi.freeze.service.PartnerAmountFreezeFlowDubboService;
import com.yunxi.hubToBiz.pojo.VehicleDeliveryOrderVO;
import com.yunxi.model.order.OrderVehicle;
import com.yunxi.model.sto.StoCarrier;
import com.yunxi.model.sto.StoVehicleDelivery;
import com.yunxi.sapToBiz.service.SapVehicleDeliveryService;
import com.yunxi.service.dubboService.impl.OrderOemManagerDubboServiceImpl;
import com.yunxi.service.localService.OrderVehicleService;
import com.yunxi.service.localService.sto.StoCarrierService;
import com.yunxi.service.localService.sto.StoVehicleDeliveryService;
import com.yunxi.sto.pojo.StoStockOutPlanVO;
import com.yunxi.sto.pojo.StoTransportPlanVO;
import com.yunxi.sto.service.StoStockOutPlanDubboService;
import com.yunxi.sto.service.StoTransportPlanDubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * SAP推送整车外向发货单到PMS 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-06-03
 */

public class SapVehicleDeliveryServiceImpl implements SapVehicleDeliveryService {

    @Autowired
    @Qualifier(value = "stoVehicleDeliveryServiceImpl")
    StoVehicleDeliveryService stoVehicleDeliveryService;

    @Autowired
    @Qualifier(value = "stoTransportPlanDubboServiceImpl")
    StoTransportPlanDubboService stoTransportPlanDubboService;

    @Autowired
    @Qualifier(value = "orderOemManagerDubboServiceImpl")
    OrderOemManagerDubboServiceImpl orderOemManagerDubboService;

    @Autowired
    @Qualifier(value = "despatchOrderDubboServiceI")
    DespatchOrderDubboService despatchOrderDubboService;

    @Autowired
    @Qualifier(value = "orderVehicleServiceImpl")
    OrderVehicleService orderVehicleService;

    @Autowired
    @Qualifier(value = "stoCarrierServiceImpl")
    StoCarrierService stoCarrierService;

    @Autowired
    @Qualifier(value = "partnerStorageDubboServiceImpl")
    PartnerStorageDubboService partnerStorageDubboService;

    @Value("${TMS.URL01}")
    private String tmsUrl01;

    @Autowired
    @Qualifier(value = "partnerAmountFreezeFlowDubboServiceImpl")
    PartnerAmountFreezeFlowDubboService partnerAmountFreezeFlowDubboService;

    @Autowired
    @Qualifier(value = "stoStockOutPlanDubboServiceImpl")
    StoStockOutPlanDubboService stoStockOutPlanDubboService;

    @Autowired
    DynamicRebateCommissionDubboService dynamicRebateCommissionDubboServiceImpl;

    private static final Logger logger = LoggerFactory.getLogger(SapVehicleDeliveryServiceImpl.class);

    /**
     * 新增整车外向发货单
     * @param list
     * @return
     * @throws Exception
     */
    @Override
    public ApiResult saveVehicleDelivery(List<VehicleDeliveryOrderVO> list) throws Exception {
        if(list != null && list.size() > 0){
            List<CanSendResourcesVO> tmsList = new ArrayList<>();
            System.out.println("saveVehicleDelivery = list = " + list.size());
            for (VehicleDeliveryOrderVO vo : list){
                StoVehicleDelivery stoVehicleDelivery = new StoVehicleDelivery();
                BeanTools.copyProperties(stoVehicleDelivery,vo);
                stoVehicleDeliveryService.saveOrUpdate(stoVehicleDelivery);
                //自动创建运输计划
                StoTransportPlanVO stoTransportPlanVO = new StoTransportPlanVO();
                stoTransportPlanVO.setVbeln(vo.getVbeln());//SAP交货单号

                //Guan 2020-02-25 大客户发送转换交车渠道商 重新定知 渠道属性便于后面赋值

                String partnerCode = vo.getKunnr();
                String pickerName  = vo.getConname();
                String pickerPhone = vo.getTelf1();
                String partnerAddr = vo.getDealeradd();
                String partnerName = "";
                String city = "";
                String province = "";

                OrderVehicle ovv = orderVehicleService.getById(vo.getBstkd());
                System.out.println("saveVehicleDelivery = 订货单号"+vo.getBstkd());
                if(StringUtils.isNotEmpty(ovv.getVipId())){
                    System.out.println("saveVehicleDelivery = 大客户处理");
                    partnerCode = ovv.getPartnerCode();
                    PartnerStorageVO psx = partnerStorageDubboService.getByPartnerVO(ovv.getPartnerCode());
                    if(psx!=null){
                        System.out.println("saveVehicleDelivery = 查到发运信息");
                        partnerAddr = psx.getAreaCodeWithName()+psx.getAddr();//渠道商收车地址
                        pickerName = psx.getLinkMan();
                        pickerPhone = psx.getLinkPhone();
                        partnerName = psx.getPartnerName();
                    }else{
                        System.out.println("saveVehicleDelivery = 没有查到发运信息");
                    }
                }else{
                    PartnerVO partnerVO = stoCarrierService.queryPartnerNameByCode(vo.getKunnr());
                    if(partnerVO!=null){
                        partnerName = partnerVO.getPartnerName();
                        city = partnerVO.getCity();
                        province = partnerVO.getProvince();
                    }
                }

                stoTransportPlanVO.setPartnerCode(partnerCode);//运达方渠道商代码
                stoTransportPlanVO.setPickerName(pickerName);
                stoTransportPlanVO.setPickerPhone(pickerPhone);
                stoTransportPlanVO.setReceiveAddress(partnerAddr);//渠道商收车地址
                stoTransportPlanVO.setVin(vo.getVhvin());//车辆VIN码
                stoTransportPlanVO.setStockOutLocation(vo.getWerks());//工厂出库地址
                stoTransportPlanVO.setOrderCarId(vo.getBstkd());//批售子单主键
                if ("02".equals(vo.getVsbed())) {
                    stoTransportPlanVO.setIsPickSelf(1);
                    //生成待出库计划,完成出库,刷新发运计划的提车日期,是否已自提状态
                    newStockOutPlan(vo);
                }
                stoTransportPlanDubboService.saveOrUpdate(stoTransportPlanVO);
                //更新订单状态,待发运
                orderOemManagerDubboService.updateOrderVehicleStatusByVin(vo.getVhvin(), Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_DELIVERY);
                //解冻资金
                partnerAmountFreezeFlowDubboService.unfreezeAmountByOrderCarId(vo.getBstkd());
                CanSendResourcesVO canSendResourcesVO = new CanSendResourcesVO();
                //获取承运商
                QueryWrapper<StoCarrier> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("IS_ON_USE",1);
                List<StoCarrier> list1 = stoCarrierService.list(queryWrapper);
                if(list1 != null && list1.size() > 0){
                    canSendResourcesVO.setCarrierCode(list1.get(0).getCarrierCode());//承运商代码
                    canSendResourcesVO.setCarrierName(list1.get(0).getCarrierName());//承运商名称
//                    canSendResourcesVO.setUrl(list1.get(0).getTmsUrl());//承运商地址
                    canSendResourcesVO.setUrl(tmsUrl01);//承运商地址
                }
                else{
                    logger.debug("================================无法获取承运商==============================!");
                }
                canSendResourcesVO.setStatus("0");
                canSendResourcesVO.setVin(vo.getVhvin());//车辆VIN码
                String modelCode = stoCarrierService.queryNodeCodeByCode(vo.getMatnr());
                canSendResourcesVO.setModelCode(modelCode);//车型代码
                //查询车型名称
                String modelName = stoCarrierService.queryNodeNameByCode(vo.getMatnr());
                canSendResourcesVO.setModelName(modelName);//车型名称
                canSendResourcesVO.setDeployCode(vo.getMatnr());//配置代码
                canSendResourcesVO.setDeployName(modelName);//配置名称
                canSendResourcesVO.setOutColor(stoCarrierService.queryOutColorName(vo.getColorid()));//外饰颜色名称
                canSendResourcesVO.setInnerColor(stoCarrierService.queryInColorName(vo.getColorin()));//内饰颜色名称

                canSendResourcesVO.setDeliveryCode(partnerCode);//运达渠道商代码
                canSendResourcesVO.setDeliveryName(partnerName);//渠道商名称
                canSendResourcesVO.setProvince(province);//省名称
                canSendResourcesVO.setCity(city);//市名称
                canSendResourcesVO.setDeliveryAddress(partnerAddr);//渠道商收车地址

                //根据PMS订单号,找到批售订单,获取物流方式
                String bstkd = vo.getBstkd();
                if(StringUtils.isNotEmpty(bstkd)){
                    QueryWrapper<OrderVehicle> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("ORDER_CAR_ID", bstkd);
                    OrderVehicle orderVehicle = orderVehicleService.getOne(queryWrapper1);
                    if(orderVehicle != null){
                        String isPickup = orderVehicle.getIsPickup();
                        if(StringUtils.isNotEmpty(isPickup) && isPickup.equals("Y")){
                            canSendResourcesVO.setVebed("02");//自提
                        }
                        else if(StringUtils.isNotEmpty(isPickup) && isPickup.equals("N")){
                            canSendResourcesVO.setVebed("01");//标准
                            tmsList.add(canSendResourcesVO);
                        }
                    }
                    else{
                        tmsList.add(canSendResourcesVO);
                    }
                }
                //update 20190815,仅推送非自提车辆到TMS
                else{
                    tmsList.add(canSendResourcesVO);
                }

                //调用资金返利
                dynamicRebateCommissionDubboServiceImpl.rebateForZiYouZiJin(vo.getBstkd());
            }
            //推送可发资源池到TMS
            despatchOrderDubboService.canSendResourcesPms2Tms(tmsList);
            return ResponseUtil.ok("新增成功");
        }
        else {
            return ResponseUtil.fail(Constant.SAP_R_CODE_ERR,"操作失败,推送内容list为空!");
        }
    }

    /**
     * 新增待出库计划
     * @param vo
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    private void newStockOutPlan(VehicleDeliveryOrderVO vo) throws Exception {
        StoStockOutPlanVO stoStockOutPlanVO = new StoStockOutPlanVO();
        stoStockOutPlanVO.setStockOutType("1");//销售出库
        stoStockOutPlanVO.setVin(vo.getVhvin());//VIN
        stoStockOutPlanVO.setPlanStockOutDate(new Date());//计划出库日期
        stoStockOutPlanVO.setDeliveryNo(vo.getVbeln());//SAP交货单号
        stoStockOutPlanDubboService.saveOrUpdate(stoStockOutPlanVO);
    }
}
